
package codeGenerate.json.generater;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import codeGenerate.common.vo.TemplateData;
import codeGenerate.json.tempalte.TemPathJsonAbstract;
import codeGenerate.json.vo.JavaClass;
import codeGenerate.json.vo.JavaField;
import codeGenerate.json.vo.JsonConfigVo;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class JsonGenerater {

	private JsonConfigVo configVo;

	public void generateCode() throws IOException, TemplateException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		System.out.println(">>>>>>>>>>>>>>>>>>>[" + configVo.getBeanDescription() + "]生成开始<<<<<<<<<<<<<<<<<<<");
		System.out.println(configVo);
		List<JavaClass> javaClassList = configVo.getJavaClassList();
		for (JavaClass javaClass : javaClassList) {
			System.out.println("===================" + javaClass.getName() + "===================");
			List<JavaField> javaFieldList = javaClass.getJavaFieldList();
			for (JavaField javaField : javaFieldList) {
				System.out.println(javaField);
			}
			System.out.println("===================" + javaClass.getName() + "===================");
		}
		Map<String, Object> root = new HashMap<String, Object>();
		//定义模板常量
		root.put("config", configVo);

		Configuration cfg = new Configuration();
		cfg.setClassicCompatible(true);
		cfg.setDirectoryForTemplateLoading(new File(configVo.getTemplateDirectory()));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		//根据模版路径生成相应的代码
		Class<?> tempateClass = Class.forName(configVo.getTemplate());
		TemPathJsonAbstract temPathAbstract = (TemPathJsonAbstract) tempateClass.newInstance();
		List<TemplateData> templateDataList = temPathAbstract.getTemplateDataList(configVo);
		for (TemplateData tp : templateDataList) {
			root.put("templateData", tp.getData());
			Template temp = cfg.getTemplate(tp.getTmpPath());
			File file = new File(tp.getGenPath());
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			OutputStream writer = new FileOutputStream(new File(tp.getGenPath()));
			Writer out = new OutputStreamWriter(writer);
			temp.process(root, out);
			writer.flush();
			writer.close();
			System.out.println("模板:" + tp.getTmpPath() + "==>>生成文件==>>" + tp.getGenPath());
		}

		System.out.println(">>>>>>>>>>>>>>>>>>>表名[" + configVo.getBeanDescription() + "]生成结束<<<<<<<<<<<<<<<<<<<");
		System.out.println("\n");
	}

	public void gen() {

	}

	public JsonConfigVo getConfigVo() {
		return configVo;
	}

	public void setConfigVo(JsonConfigVo configVo) {
		this.configVo = configVo;
	}

}
